package com.stbu;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;

@Controller
public class FileController {
    @RequestMapping("/toUpload")
    public String toUploadFile(){
        return "upload";
    }
    @PostMapping("/upload")
    public ModelAndView upload(@RequestPart("myFile") MultipartFile file){
        ModelAndView view = new ModelAndView();

        String destString = System.getProperty("user.home") + File.separator + "Desktop"
                + File.separator + "Upload files" + File.separator;
        File destFile = new File(destString);
        if(!destFile.exists()){
            destFile.mkdir();
        }

        System.out.println("目标文件路径"+ destFile.getAbsolutePath());

        File destFinal = new File(destFile,file.getOriginalFilename());
        System.out.println("上传目标全路径"+destFinal.getAbsolutePath());
        String msg = "";
        try {
            file.transferTo(destFinal);
            msg = "上传成功";
        }catch (IOException e){
            e.printStackTrace();
            msg = "上传失败";
        }
        view.addObject("msg",msg);
        view.setViewName("info");

        return view;
    }
}
